package org.example.Forms;

import org.example.Controller.FormManagerNode;
import org.example.Event.BasicEvent;
import org.example.Event.EventManager;
import org.example.Tool.IRunFunc;

import javax.swing.*;
import javax.xml.transform.Source;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.function.Function;


public abstract class AbstractForm  implements IForm{
    protected Source source = new Source() {
        String id;{
            id = this.toString();
        }
        @Override
        public void setSystemId(String systemId) {
            systemId = id;
        }

        @Override
        public String getSystemId() {
            return id;
        }
    };



    protected JFrame frame;

    protected final FormManagerNode node;

    public AbstractForm(FormManagerNode node){
        frame = new JFrame();
        this.node = node;

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                exit();
                //SendExitMessage
                EventManager.informListeners(
                        new BasicEvent(source, BasicEvent.EventType.FormClosing)
                );
            }
        });
    }
    protected abstract void exit();


    public FormManagerNode createNewForm(Function<FormManagerNode,IForm> factory){
        return new FormManagerNode(factory,this.node);
    }

    @Override
    public void show() {
        frame.setVisible(true);
    }

    public String getSystemId() {
        return source.getSystemId();
    }


//    public static class Builder{
//        private IForm buildBody;
//        private FormManagerNode parentNode;
//
//        private Function<IForm, Function<FormManagerNode,IForm>> factory;
//        public Builder(FormManagerNode parentNode){
//            this.parentNode = parentNode;
//        }
//        public IForm of(){
//            buildBody = factory.apply(buildBody).apply(parentNode);
//
//              buildBody = new AbstractForm(new FormManagerNode(buildBody,parentNode)) {
//                  @Override
//                  public void show() {
//                      frame.setVisible(true);
//                  }
//
//                  @Override
//                  protected void exit() {
//
//                  }
//              };
//            return buildBody;
//        }
//    }
}
